package com.infopatent.shldevtools.tools;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.log4j.Logger;

/**
 * 操作和制作PDF文件的工具类
 *
 * @author shaohailong
 */
public class MySimplePdfTools {
    
     
    private static MySimplePdfTools mySimplePdfUtil;
    private static Logger log = Logger.getLogger(MySimplePdfTools.class);
    
    static {
        mySimplePdfUtil = new MySimplePdfTools();
    }

    /**
     * 无参构造方法
     */
    private MySimplePdfTools() {
    }

    /**
     * 
     * @return 获得该工具类的实例
     */
    public static MySimplePdfTools getInstance() {
        return mySimplePdfUtil;
    }

    /**
     * 得到生成的PDF文件（多个合并）
     *
     * @param savepath 文件保存的路径
     * @param rName 报表名称
     * @param files 生成的文件
     * @return String
     */
    public String getMergedPDF(String savepath, String rName, String[] files) {
        String getResultName = null;
        
        File savePath = new File(savepath,rName+".pdf");
        if(!savePath.getParentFile().exists()){
            savePath.getParentFile().mkdirs();
        }
        
        savepath = savePath.getPath();
//如果是多个PDF文件进行合并 
        if (files.length > 1) {
//多个PDF文件合并 
            mergePdfFiles(files, savepath);
            getResultName = savepath.subSequence(savepath.lastIndexOf(File.separator),savepath.length()).toString();
        } else {
            if (reNameFile(files, savepath)) {
                getResultName = rName + ".pdf";
            }
        }
        return getResultName;
    }

    /**
     * 多个PDF合并功能
     *
     * @param files 多个PDF的路径
     * @param savepath 生成的新PDF路径
     * @return boolean boolean
     */
    public static boolean mergePdfFiles(String[] files, String savepath) {
        try {
            Document document = new Document(new PdfReader(files[0]).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            document.close();
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return false;
        } catch (DocumentException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 文件重命名
     */
    public static boolean reNameFile(String[] oldName, String newName) {
        File oldfile = null;
        if (oldName != null) {
            for (int i = 0; i < oldName.length; i++) {
                oldfile = new File(oldName[i]);
            }
            if (oldfile == null) {
                return false;
            }
            File newfile = new File(newName);
            if (oldfile.renameTo(newfile)) {
                return true;
            }
        }
        return false;
    }
    
    
    /**
     *
     * @param targetDir 目标目录,生成的PDF文件会在这个路径下
     * @param targetPDFFileName 目标文件,生成的PDF文件名称在这里定义
     * @param pageWidth 转换的PDF文档的页宽,例如一页显示一个tiff,那么这里是tiff文件的宽度 使用float类型 推荐
     * 595.4f
     * @param pageHeight 转换的PDF文档的页高,例如一页显示一个tiff,那么这里是tiff文件的高度 使用float类型 推荐
     * 842f
     * @param tiffs 需要转换的tiff文件全路径的字符串数组
     * @param marginTop 上边距
     * @param marginRight 右边距
     * @param marginBottom 下边距
     * @param marginLeft 左边距
     * @return
     */
    public void TiffsToPDF(String targetDir, String targetPDFFileName, float pageWidth, float pageHeight, String[] tiffs, float marginTop, float marginRight, float marginBottom, float marginLeft) {
        File tdir = new File(targetDir);
        if (!tdir.exists()) {
            tdir.mkdirs();
        }

        String tiff;
        //初始化PDF文档,并且设置每页的长宽以及外边距(这里外边距均为0)
        Document document = new Document(new Rectangle(pageWidth, pageHeight), marginLeft, marginRight, marginTop, marginBottom);
        try {
            try {
                PdfWriter.getInstance(document, new FileOutputStream(targetDir + File.separator + targetPDFFileName));
            } catch (DocumentException ex) {
                log.error(ex.getMessage(), ex);
            }
        } catch (FileNotFoundException ex) {
            log.error(ex.getMessage(), ex);
        }
        document.open();
        for (int i = 0; i < tiffs.length; i++) {
            tiff = tiffs[i];
            try {
                System.out.println("Processing: " + tiff);
                try {
                    Image img = Image.getInstance(tiff);
                    if (img != null) {
                        System.out.println("page " + (i + 1));
                        //TODO
//                        img.getScaledWidth();
//                        img.getScaledHeight();
//                        img.scalePercent(2480f / img.getDpiX(), 3508f / img.getDpiY());
//                        img.getAbsoluteX();
//                        img.getAbsoluteY();
//                        img.getPlainWidth();
//                        img.getPlainHeight();
//                        document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
//                        img.setAbsolutePosition(0, 0);
//                        document.setPageSize(img);
                        img.scalePercent(((pageWidth-marginLeft-marginRight)*100)/img.getPlainWidth(), ((pageHeight-marginTop-marginBottom)*100)/img.getPlainHeight());
//                        img.setAbsolutePosition(0, 0);
                        img.setAlignment(Element.ALIGN_CENTER);
                        
                        document.add(img);
                        document.newPage();
                    }
                } catch (Throwable e) {
                    System.out.println("Exception " + tiff + " page " + (i + 1) + " " + e.getMessage());
                    log.error(e.getMessage(), e);
                }
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
            System.out.println("done...");
        }
        document.close();
    }

    public static void main(String[] args) {
        String saveLocation = "D://temp/";
        String reportName = "用户流量分布";
        File fileDir = new File("C:\\Users\\Administrator\\Desktop\\all4one");
        String[] pdfFileNames;
        pdfFileNames = fileDir.list();
        String[] pdfFilePaths = new String[pdfFileNames.length];
        int i = 0;
        for (String fileName : pdfFileNames) {
            pdfFilePaths[i] = new File(fileDir.getPath(),fileName).getPath();
            i++;
        }
        System.out.println(pdfFilePaths.length);       
        
        String files[] = new String[]{"D:/temp/aa.pdf", "D:/temp/bb.pdf"};
        new MySimplePdfTools().getMergedPDF(saveLocation, reportName, pdfFilePaths);
    }
}
